package com.xjm_cloud_admin.security.service;

import com.xjm_cloud_admin.constant.HttpStatus;
import com.xjm_cloud_admin.domain.XjmUser;
import com.xjm_cloud_admin.enums.CommonCodeEnum;
import com.xjm_cloud_admin.exception.CustomException;
import com.xjm_cloud_admin.security.pojo.LoginUser;
import com.xjm_cloud_admin.service.XjmUserService;
import com.xjm_cloud_admin.util.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户验证处理
 *
 * @author 浪漫写尽歌谱
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private XjmUserService xjmUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        XjmUser user = null;
        try {
            user = xjmUserService.selectUserByUserName(Long.valueOf(username));
        } catch (NumberFormatException e) {
            throw new CustomException(HttpStatus.SHOW_TOAST, "不支持的邮箱格式");
        }
        if (StringUtils.isNull(user)) {
            throw new CustomException(HttpStatus.SHOW_TOAST, "用户不存在");
        } else if (CommonCodeEnum.one.getCode().equals(user.getStatus())) {
            throw new CustomException(HttpStatus.SHOW_TOAST, "该账号已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(XjmUser user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setXjmUser(user);
        return loginUser;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String admin = bCryptPasswordEncoder.encode("admin");
        System.out.println(admin);
    }

}
